/*
 * @Author: LBH 1336709799@qq.com
 * @Date: 2024-10-29 09:10:20
 * @LastEditors: LBH 1336709799@qq.com
 * @LastEditTime: 2024-10-31 10:37:00
 * @FilePath: \enjoy_plus_three\lib\utils\http.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'package:dio/dio.dart';
import 'package:enjoy_plus_three/utils/eventbus.dart';
import 'package:enjoy_plus_three/utils/token.dart';

class NetworkService{
  final _dio = Dio();

  NetworkService(){
    // 配置基础地址
    _dio.options.baseUrl = 'https://live-api.itheima.net';
    // 设置连接超时时间
    _dio.options.connectTimeout = const Duration(seconds: 5);
    // 设置接收超时时间
    _dio.options.receiveTimeout = const Duration(seconds: 5);
    // 设置请求头
    _dio.options.headers = {'Content-Type': 'application/json'};
    _addInterceptors();

  }

  // 发起GET请求
  // url请求的URL
  // params请求的查询参数
  // 返回解析后的响应数据或错误信息
  Future<dynamic> get(String url,{Map<String,dynamic>? params}) async{
    try{
      final response  = await _dio.get(url,queryParameters: params);
      return handleResponse(response);
    }catch(e){
      return handleError(e);

    }
  }

  // 发起POST请求
  // url请求的URL
  // data请求的主体数据
  // 返回解析后的响应数据或错误信息
  Future<dynamic> post(String url,dynamic data)async{
    try{
      final response  = await _dio.post(url,data: data);
      return handleResponse(response);
    }catch(e){
      return handleError(e);

    }

  }

  void _addInterceptors(){
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (RequestOptions options,RequestInterceptorHandler handler) async{
        // 请求拦截器,添加公共请求参数,token等
        final token = TokenManager().getToken() ?? '';
        if(token.isNotEmpty){
          options.headers['Authorization'] = 'Bearer $token';
        }
        return handler.next(options);
      },
      onResponse:(response,handler){
        // 响应拦截器,统一处理成功响应
        return handler.next(response);
      },
      onError: (DioException error,handler){
        // 响应拦截器,统一处理错误响应
        return handler.next(error);
      }
    ));
  }



  dynamic handleResponse(Response response) {
    // 加类型断言,因为可能为空
    if (response.statusCode! >= 200 && response.statusCode! < 300) {
      return response.data;
    } else {
      throw Exception('请求失败，状态码：${response.statusCode}');
    }
  }

  dynamic handleError(error) {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('网络连接超时');
      } else if (error.type == DioExceptionType.badResponse) {
        if(error.response?.statusCode == 401){
          TokenManager().removeToken();
          // 通过事件通知登录页面退出登录
          // 派发事件 - 跳转到登录页
          eventBus.fire(Logout());
        }else{
          throw Exception('响应错误');
        }
      } else {
        throw Exception('网络请求错误：$error');
      }
    } else {
      throw Exception('未知错误：$error');
    }
  }
  
}

// 导出
final http = NetworkService();
